#include "messageevent.h"
#include "converse/conversegroupconversation.h"
#include "converse/converseprivateconversation.h"
#include "converse/conversemanager.h"
#include "appchat/accountmanager.h"
#include "account/accountmember.h"
#include "converse/converseabstractmessage.h"

#include "contact/contactabstractcontact.h"
#include "contact/contactprivatecontact.h"
#include "contact/contactmanager.h"


#include <QDebug>


MessageEvent::MessageEvent(qint64 id,
                           qint64 sendingId,
                           qint64 conversationId,
                           qint64 createdTime,
                           qint64 senderId,
                           qint64 receiverId,
                           QObject *parent) :
    AbstractEvent(parent),
    m_id(id),
    m_sendingId(sendingId),
    m_conversationId(conversationId),
    m_createdTime(createdTime),
    m_senderId(senderId),
    m_receiverId(receiverId)
{
}


AbstractEvent::EventType
MessageEvent::eventType() const
{
    return AbstractEvent::MessageEvent;
}


void MessageEvent::process()
{
    qDebug() << "void MessageEvent::process()";

    Converse::Manager *manager = Converse::Manager::instance();
    Converse::AbstractConversation *conversation = manager->findBySending(m_sendingId);

    if (conversation != NULL) {
        manager->changePrivateConversationId(conversation, m_conversationId);
    } else {
        conversation = manager->findPrivateConversationById(m_senderId);
        if (conversation != NULL) {
            manager->changePrivateConversationId(conversation, m_conversationId);
        } else {
            conversation = manager->findPrivateConversationById(m_conversationId);
            if (conversation == NULL) {
                qDebug() << "void MessageEvent::process() m_senderId " << m_senderId;

                qint64 fid;
                if (AccountManager::instance()->getUserId() == m_senderId) {
                    fid =  m_receiverId;
                } else {
                    fid = m_receiverId;
                }
                Contact::PrivateContact *contact = \
                        Contact::Manager::instance()->findPrivateContactById(fid);
                if (contact == NULL)
                    return;

                conversation = Converse::Manager::instance()->appendPrivateConversation(conversationId(), contact);
            }
        }
    }

    conversation->receive(*this);
}
